#include "cgamestate.h"
#include "cmenustate.h"
#include "math.h"
#include <QGLWidget>
#include <iostream>

CGameState CGameState::st_game;

void CGameState::draw(QGLWidget * gl)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glColor3f(1.0f, 1.0f, 1.0f);
    glBindTexture(GL_TEXTURE_2D,texture[0]);
    glBegin(GL_QUADS);  // fonas
        glTexCoord2f(0.0f,0.0f); glVertex3i(  0, 0,-100);
        glTexCoord2f(0.0f,1.0f); glVertex3i(  0, 600,-100);
        glTexCoord2f(1.0f,1.0f); glVertex3i(800, 600,-100);
        glTexCoord2f(1.0f,0.0f); glVertex3i(800, 0,-100);
    glEnd();

    glLoadIdentity();
    glTranslatef(gl->width()/2,gl->height()/2,0.0f);
    glDisable(GL_TEXTURE_2D);
    glColor3f(1.0f, 1.0f, 0.0f);
    glBegin(GL_TRIANGLES);
    if (ornt == 0) {                // Žiūri į priekį
        glVertex3i(    x, 30+y,0);
        glVertex3i(-30+x,-30+y,0);
        glVertex3i(+30+x,-30+y,0);
    } else if (ornt == 1) {         // į kairę
        glVertex3i(-30+x,    y,0);
        glVertex3i(+30+x,-30+y,0);
        glVertex3i(+30+x,+30+y,0);
    } else if (ornt == 2) {         // į dešinę
        glVertex3i(+30+x,    y,0);
        glVertex3i(-30+x,+30+y,0);
        glVertex3i(-30+x,-30+y,0);
    } else if (ornt == 3) {
        glVertex3i(    x,-30+y,0);  // į apačią
        glVertex3i(-30+x,+30+y,0);
        glVertex3i(+30+x,+30+y,0);
    }
    glEnd();
    glEnable(GL_TEXTURE_2D);

}

void CGameState::enterState()
{
    std::cout << "! Aktyvuotas Game state " << std::endl;
}

void CGameState::leaveState()
{
    std::cout << "- Deaktyvuotas Game state " << std::endl;
}

void CGameState::update()
{

}

void CGameState::initVars()
{
    x = 0; y = 0; ornt = 0;
}

void CGameState::initGL(QGLWidget *gl)
{
    glDisable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    //gl->makeCurrent();
    texture[0] = gl->bindTexture(QPixmap(QString("../img/earth.jpg")), GL_TEXTURE_2D);
    glEnable(GL_TEXTURE_2D);
    //glColor4f(1.0f,1.0f,1.0f,1.0f);
    //glEnable(GL_BLEND);
    //glEnable(GL_ALPHA_TEST);
    //glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
    //glAlphaFunc(GL_GREATER,0.1f);
}

int CGameState::doLogic(QList<int> Kl)
{
    // ornt - trikampiuko orientacija
    //  + šioks toks CD
    if (Kl.contains(Qt::Key_Up)) {
       ornt = 0; if ((y + 35) <  300) y += 5;
    }
    else if(Kl.contains(Qt::Key_Down)) {
       ornt = 3; if ((y - 35) > -300) y -= 5;
    }
    else if (Kl.contains(Qt::Key_Left)) {
       ornt = 1; if ((x - 35) > -400) x -= 5;
    }
    else if (Kl.contains(Qt::Key_Right)) {
       ornt = 2; if ((x + 35) <  400) x += 5;
    }
    else if (Kl.contains(Qt::Key_Space)) {
       ornt = 0; x = 0; y = 0;
    }
    else if (Kl.contains(Qt::Key_Escape)) {
        if (p_stMngr != NULL)
           changeState(p_stMngr, CMenuState::instance());
    }

    return 0;
}
